/**
 * @author cqg001
 * @description 主要用来解决token拦截的安全问题
 * @copyright 大连大学图灵工作室
 * @version 1.0
 */
const jwt = require('jsonwebtoken')
const fs = require('fs')
const path = require('path')
const public_key = fs.readFileSync(path.join(__dirname, '../../key/rsa_public_key.pem'))

const token = function (req, res, next) {
    // 不做token验证的白名单
    const reg = /\/static|\/login|\/regist|\/pro|\/banner|\/brand|\/category|\/comment|\/up|\/footprint/
    const result = {
        code: 10119,
        msg: '请先登录'
    }
    if (reg.test(req.url)) {
        next()
    } else {
        try {
            const obj = jwt.verify(req.headers.token, public_key)
            if (Object.keys(obj).includes('password')) {
                next()
            } else {
                res.send(JSON.stringify(result))
            }
        } catch (e) {
            res.send(JSON.stringify(result))
        }
    }
}
module.exports = token
